package com.example.mytestapplication;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mytestapplication.bean.BoxDeviceVo;
import com.example.mytestapplication.bean.DataValue;
import com.example.mytestapplication.utils.LiefengRetrofit;
import com.example.mytestapplication.utils.PreferencesLoader;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.prefs.Preferences;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.R.attr.logo;
import static android.R.attr.x;

public class MainActivity extends Activity {

    private static String LOG_TAG = "WifiBroadcastActivity";

    private volatile boolean start = true;

    private volatile String address = null;
    public static final int DEFAULT_PORT = 43708;
    private static final int CLIENT_PORT = 43608;
    private static final int MAX_DATA_PACKET_LENGTH = 40;
    private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];

    private Button qipButton;
    private Button qdevButton;
    private Button sendButton;
    private Button openButton;
    private Button closeButton;

    private EditText command;
    private Spinner boxlist;
    private EditText message;

    final List<String> boxitems = new ArrayList<>();
    ArrayAdapter<String> adapter;
    private UdpHelper udpHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreferencesLoader.init(getApplicationContext());
        EventBus.getDefault().register(this);
        initOpenId();

        command = (EditText) this.findViewById(R.id.edit_command);
        boxlist = (Spinner) findViewById(R.id.address_list);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, boxitems);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        boxlist.setAdapter(adapter);
        boxlist.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                address = boxitems.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                address = "";
            }
        });

        qipButton = (Button) this.findViewById(R.id.button_query_ip);
        qdevButton = (Button) this.findViewById(R.id.button_query_device);
        sendButton = (Button) this.findViewById(R.id.button_send);
        openButton = (Button) findViewById(R.id.button_open);
        closeButton = (Button) findViewById(R.id.button_close);
        message = (EditText) this.findViewById(R.id.tv_message);

//        UdpReceiver thread = new UdpReceiver();
//        thread.setPriority(Thread.MAX_PRIORITY);
//        thread.start();
        udpHelper = UdpHelper.getInstance(this);
        udpHelper.startReadThread();
        message.append("\n");

        udpHelper.setBoxIdRequirtListener(new UdpHelper.BoxIdRequirtListener() {
            @Override
            public void requirt(String boxIp) {
                Message msg = new Message();
                msg.what = 1;
                msg.obj = boxIp;
                mHandler.sendMessage(msg);
            }
        });

        //address = getLocalIPAddress();
        //if (address != null) {
        //    IPAddress.setText(address);
        //} else {
        //    IPAddress.setText("Can not get IP address");
        //    return;
        //}

        sendButton.setOnClickListener(listener);
        openButton.setOnClickListener(listener);
        closeButton.setOnClickListener(listener);
        qipButton.setOnClickListener(listener);
        qdevButton.setOnClickListener(listener);

        System.out.println("启动成功！");
        startService(new Intent(getApplicationContext(),RecordService.class));
    }

    @Subscriber(tag = "UNCONNECT_NETWORK")
    private void unconnectNetwork(String s){
        Toast.makeText(this, "网络连接断开"+s, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    private static String TAG = "MainActivity";
    private void initOpenId() {
        LiefengRetrofit.getInstance().getTvBoxApi()
                .getBoxByWirelessMac("18:82:19:87:3B:AD")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new NetworkObserver<DataValue<BoxDeviceVo>>() {
                    @Override
                    public void onError2(Throwable e) {
                        Log.d(TAG, "onError2: "+e.getMessage());
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onNext(DataValue<BoxDeviceVo> boxDeviceVoDataValue) {
                        Log.d(TAG, "onNext: ");
                    }
                });

        LiefengRetrofit.getInstance().getTvBoxApi()
                .getBoxByWirelessMac("18:82:19:87:3B:AD")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<DataValue<BoxDeviceVo>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        if (e != null) {
//                            if(e instanceof UnknownHostException){
//                                Toast.makeText(MainActivity.this, "网络断开了", Toast.LENGTH_SHORT).show();
//                            }
//                            Log.d(TAG, "onError: "+e);
//                            Log.d(TAG, "onError: "+e.getMessage());
//                            Log.d(TAG, "onError: "+e.getCause());
//                        }
                    }

                    @Override
                    public void onNext(DataValue<BoxDeviceVo> boxDeviceVoDataValue) {
                        if (!boxDeviceVoDataValue.isSuccess()) {
                            Log.e(TAG, boxDeviceVoDataValue.getDesc());
                            return;
                        }

                        if (boxDeviceVoDataValue.getData() == null || TextUtils.isEmpty(boxDeviceVoDataValue.getData().getFamilyId())) {
                            Log.e(TAG, "family id is empty");
                            return;
                        }
                        Log.d(TAG, "onNext: "+boxDeviceVoDataValue.getData().getOpenId());
                        PreferencesLoader.getAppPreferences().put("openid",boxDeviceVoDataValue.getData().getOpenId());


                    }
                });
    }

    public static String getWifiMacAddr(Context context) {
        WifiManager wifi=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info=wifi.getConnectionInfo();
        String macAddr="";
        if (null!=info) {
            String addr=info.getMacAddress();
            if (null!=addr) {
                macAddr=addr;
            }
        }
        return macAddr;
    }

    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == qipButton) {
                System.out.println("启动查IP");
//                new BroadCastUdp("qip").start();
                UdpHelper.getInstance(MainActivity.this).sendThread("qip");
            } else if (v == qdevButton) {
                System.out.println("启动查设备");
//                new BroadCastUdp("qdev").start();
                UdpHelper.getInstance(MainActivity.this).sendThread("qdev");
            } else if (v == sendButton) {
                System.out.println("启动发送命令");
//                new BroadCastUdp(command.getText().toString()).start();
                UdpHelper.getInstance(MainActivity.this).sendThread((command.getText().toString()));
            } else if (v == openButton) {
                System.out.println("启动开灯");
                UdpHelper.getInstance(MainActivity.this).sendThread("cmd=735000004,N1#");
//                new BroadCastUdp("cmd=735000004,N1#").start();
//                new BroadCastUdp("cmd=735000004,N2#").start();
//                new BroadCastUdp("cmd=735000004,N3#").start();
//                new BroadCastUdp("cmd=715000008,N1#").start();

//                new BroadCastUdp("cmd=810000568,N1#").start();
                //start = false;
            } else if (v == closeButton) {
                System.out.println("启动关灯");
//                new BroadCastUdp("cmd=735000004,F1#").start();
                UdpHelper.getInstance(MainActivity.this).sendThread("cmd=735000004,F1#");
//                new BroadCastUdp("cmd=735000004,F2#").start();
//                new BroadCastUdp("cmd=735000004,F3#").start();
//                new BroadCastUdp("cmd=715000008,F1#").start();
//                new BroadCastUdp("cmd=810000568,F1#").start();
            }
        }
    };

    private String getLocalIPAddress() {
        String ret = null;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    Log.d("ip", inetAddress.toString());
                    if (inetAddress.isSiteLocalAddress()) {
                        ret = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            System.out.println("出错：" + ex.toString());
        }
        return ret;
    }

    //写线程
    public class BroadCastUdp extends Thread {
        private String dataString;
        private DatagramSocket udpSocket;

        public BroadCastUdp(String dataString) {
            this.dataString = dataString;
        }

        @Override
        public void run() {
            DatagramPacket dataPacket = null;

            try {

                udpSocket = new DatagramSocket(DEFAULT_PORT);
                dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
                byte[] data = dataString.getBytes();
                dataPacket.setData(data);
                dataPacket.setLength(data.length);
                dataPacket.setPort(DEFAULT_PORT);
                InetAddress addr;
                if (address == null || address.isEmpty()) {
                    addr = InetAddress.getByName("255.255.255.255");
                } else {
                    addr = InetAddress.getByName(address);
                }
                System.out.println("发给：" + addr.getHostAddress().toString());
                dataPacket.setAddress(addr);

            } catch (Exception e) {
                Log.e(LOG_TAG, e.toString());
            }
//            while (start) {
            try {
//                System.out.println("准备：");
                if (udpSocket != null) {
                    udpSocket.send(dataPacket);
                    System.out.println("已发送：" + new String(dataPacket.getData()));
                }
                //sleep(5000);
            } catch (Exception e) {
                System.out.println("error：" + e.toString());
            }
//            }
            udpSocket.close();
            System.out.println("关闭。");
        }
    }

    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1)
            {
                if (!boxitems.contains(msg.obj))
                    boxitems.add(msg.obj.toString());
                adapter.notifyDataSetChanged();
            }
        }
    };

    //读线程
    private class UdpReceiver extends Thread {

        @Override
        public void run() {
            DatagramSocket ds = null;
            DatagramPacket dp = null;
            byte[] dataRecv = new byte[1024];
            System.out.println("UdpReceiver started >>>>>");
            try {
                ds = new DatagramSocket(CLIENT_PORT);
                dp = new DatagramPacket(dataRecv, dataRecv.length);
            } catch (SocketException e) {
                e.printStackTrace();
            }
            while (start) {
                try {
                    System.out.println("接收ing");
                    ds.receive(dp);
                    System.out.println("接收done");
                    if (dp.getAddress() != null) {
                        final String codeString = new String(dataRecv, 0, dp.getLength());
                        final String boxIp = dp.getAddress().toString().substring(1);
                        if (codeString.contains("qip") ||
                                codeString.contains("rpt")
                                || codeString.contains("device")) {


                        }
                        System.out.println("recv:" + codeString + " from:" + boxIp);
                        message.post(new Runnable() {
                            @Override
                            public void run() {
                                message.append("\nTV Box:"+boxIp+" return>>>>>>\n");
                                message.append(codeString + "\n<<<<<<");
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ds != null) {
                ds.close();
            }
            System.out.println("recv:close");
        }
    }


}